<?php
use lib\{Examine,PayUtils,AesRsa_Encrypter};
/**
 * 创建异步回调URL
 *
 * @param array $data 包含回调信息的关联数组
 * @return array 包含通知和返回 URL 的关联数组
 */
function creat_callback($data){//异步回调
    global $date;
    // 检查$data是否为空
    if (empty($data)) {
        return false;
    }
    // 检查$data中的关键参数是否为空
    $requiredFields = ['pid', 'trade_no', 'out_trade_no', 'type', 'name', 'money'];
    foreach ($requiredFields as $field) {
        if (empty($data[$field])) {
            return false;
        }
    }
    $userrow = Examine::getDB()->userrow($data['pid'],'pid');
    $key = $userrow['key'];
    $type = $data['type'];
    $array=array('pid'=>$userrow['pid'],'trade_no'=>$data['trade_no'],'out_trade_no'=>$data['out_trade_no'],'type'=>$type,'name'=>$data['name'],'money'=>(float)$data['money'],'trade_status'=>'TRADE_SUCCESS');
    if(!empty($data['param']))$array['param']=$data['param'];
    $arg=PayUtils::argSort(PayUtils::paraFilter($array));
    $prestr=PayUtils::createLinkstring($arg);
    $urlstr=PayUtils::createLinkstringUrlencode($arg);
    $sign=PayUtils::md5Sign($prestr, $key);
    
    if($userrow['api_mode'] == 2){
	    $array['sign'] = $sign;
	    
	    $arr = [
	        'pid'=>$userrow['pid'],
	        'token'=>AesRsa_Encrypter::encode(json_encode($array),md5($key.$userrow['pid']),$userrow['rsapublickey'])
	   ];
	  
	   $arg=PayUtils::argSort(PayUtils::paraFilter($arr));
	   
	   $urlstr=PayUtils::createLinkstringUrlencode($arg);
	   $sign = 'TRADE_SUCCESS';
	}
	
    // 更新用户额度
    if ($data['status'] == 0) {
        Examine::getDB()->update('user',['money'=>$userrow['money'] - $data['price']] , ['pid'=>$data['pid']]);
    }
    Examine::getDB()->update('order',['status'=>1,'endtime'=>$date],['trade_no'=>$data['trade_no']]);
    
    
    // 检查 notify_url 是否包含查询参数
    if (strpos($data['notify_url'], '?') !== false) {
        $url['notify'] = $data['notify_url'] . '&' . $urlstr . '&sign=' . $sign . '&sign_type=MD5';
    } else {
        $url['notify'] = $data['notify_url'] . '?' . $urlstr . '&sign=' . $sign . '&sign_type=MD5';
    }
    
    // 检查 return_url 是否包含查询参数
    if (strpos($data['return_url'], '?') !== false) {
        $url['return'] = $data['return_url'] . '&' . $urlstr . '&sign=' . $sign . '&sign_type=MD5';
    } else {
        $url['return'] = $data['return_url'] . '?' . $urlstr . '&sign=' . $sign . '&sign_type=MD5';
    }
    return $url;
}

function do_notify($url,$send = false){
	$return = get_curl($url);
	if(strpos($return,'success')!==false || strpos($return,'SUCCESS')!==false || strpos($return,'Success')!==false){
	    if($send)return $return;
		return true;
	}else{
		return false;
	}
}

?>